package com.wanbatv.wangwangba;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.wanbatv.kit.messenger.Letter;
import com.wanbatv.kit.messenger.MessageSubscriber;
import com.wanbatv.kit.messenger.MessengerClient;
import com.wanbatv.kit.messenger.Option;
import com.wanbatv.wangwangba.util.BitmapCache;
import com.wanbatv.wangwangba.util.FocusImageView;
import com.wanbatv.wangwangba.util.Util;
import com.wanbatv.wangwangba.utils.Product;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * Created by Forcs on 15/10/31.
 */
public class JournalActivity extends FullScreenActivity {

    // 微信头像列表
    private LinearLayout mLlyUserList = null;
    // 微信照片视频封面列表
    private RecyclerView mRycMediaList = null;
    // 微信照片视频封面列表的布局管理器
    private CoverListSpanSizeLookup mLookup = null;
    private GridLayoutManager mLayoutManager = null;
    // 适配器
    private CoverListAdapter mAdapter = null;

    // 封面类型：图片
    private static final int COVER_TYPE_IMAGE = 1;
    // 封面类型：视频
    private static final int COVER_TYPE_VIDEO = 2;

    // 封面列表元素类型：日期
    private static final int ITEM_TYPE_DATE = 1;
    // 封面列表元素类型：封面
    private static final int ITEM_TYPE_COVER = 2;
    // 封面列表默认一行显示5个
    private static final int DEFAULT_SPAN_COUNT = 5;

    private ImageLoader mImageLoader;
    private RequestQueue mQueue;

    // 用户列表
    private UserItem[] mUserList = null;
    // 媒体列表的原始数据
    private RawMediaItem[] mRawMediaList = null;
    // 按日期整理后的分组列表
    private List<BaseItem> mItems = null;

    // 用户列表加载完成的消息标识
    private static final int MSG_LOAD_USER_LIST_DONE = 1;
    // 媒体列表加载完成的消息标识
    private static final int MSG_LOAD_MEDIA_LIST_DONE = 2;
    // 数据加载错误的消息标识
    private static final int MSG_LOAD_DATA_ERROR = 3;

    private Handler mHandler = null;
    // 解决Handler内部实例导致Activity内存泄露的问题
    private static class LoadDataHandler extends Handler {

        private WeakReference<JournalActivity> mContextRef = null;

        public LoadDataHandler(JournalActivity activity) {
            super(Looper.getMainLooper());
            mContextRef = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            JournalActivity context = mContextRef.get();
            if (context != null) {
                switch (msg.what) {
                    case MSG_LOAD_MEDIA_LIST_DONE:
                        context.loadMediaListDone();
                        break;
                    case MSG_LOAD_USER_LIST_DONE:
                        context.loadUserListDone();
                        break;
                    case MSG_LOAD_DATA_ERROR:
                        context.loadDataError((String) msg.obj);
                        break;
                }
            }
        }
    }

    private ImageView chengzhangriji_bianji_iv;
    private ImageView chengzhangriji_wancheng_iv;
    private boolean isbianji=false;

    private MessageSubscriberImpl mMessageSubscriber = new MessageSubscriberImpl();
    private MessengerClient mMessengerClient = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_journal);
        mLlyUserList = (LinearLayout) findViewById(R.id.avator_list);
        mRycMediaList = (RecyclerView) findViewById(R.id.cover_list);
        chengzhangriji_bianji_iv=(ImageView)findViewById(R.id.chengzhangriji_bianji_iv);
        chengzhangriji_wancheng_iv=(ImageView)findViewById(R.id.chengzhangriji_wancheng_iv);
        mLayoutManager = new GridLayoutManager(this, DEFAULT_SPAN_COUNT);
        mLookup = new CoverListSpanSizeLookup();
        mLayoutManager.setSpanSizeLookup(mLookup);
        mAdapter = new CoverListAdapter(getApplicationContext(), new CoverListAdapterDelegate() {
            @Override
            public void onScorllToListItem(long id) {}

            @Override
            public void onScorllToFirstRow() {
                mRycMediaList.smoothScrollToPosition(0);
            }
        });
        mRycMediaList.setLayoutManager(mLayoutManager);
        mRycMediaList.setAdapter(mAdapter);

        mQueue = Volley.newRequestQueue(getApplicationContext());
        mImageLoader = new ImageLoader(mQueue, new BitmapCache());

        mHandler = new LoadDataHandler(this);
        // 加载数据
        loadData();

        chengzhangriji_bianji_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开编辑模式，隐藏编辑按钮，显示完成按钮
                isbianji=true;
                chengzhangriji_wancheng_iv.setVisibility(View.VISIBLE);
                chengzhangriji_wancheng_iv.requestFocus();
                v.setVisibility(View.GONE);
                mAdapter.onEditMode();
            }
        });
        chengzhangriji_wancheng_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭编辑模式，显示编辑按钮，隐藏完成按钮
                isbianji=false;
                chengzhangriji_bianji_iv.setVisibility(View.VISIBLE);
                chengzhangriji_bianji_iv.requestFocus();
                v.setVisibility(View.GONE);
                mAdapter.offEditMode();
            }
        });

        Option option = new Option();
        option.appId = Product.appId;
        option.appKey = Product.appKey;
        option.group = Product.flavor;
        option.device = Util.getDeviceId(this);
        mMessengerClient = MessengerClient.getInstance(this, option);
    }

    private void loadData() {
        JsonObjectRequest request = new JsonObjectRequest(
                "http://121.201.14.248/wangwangba/data.jsp?userId=" + Util.getDeviceId(getApplicationContext()), null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        if (jsonObject.has("userList")) {
                            try {
                                JSONArray userList = jsonObject.getJSONArray("userList");
                                final int count = userList.length();
                                mUserList = new UserItem[count];
                                for (int i = 0; i < count; i++) {
                                    UserItem userItem = new UserItem();
                                    userItem.decode(userList.getJSONObject(i));
                                    mUserList[i] = userItem;
                                }
                                mHandler.sendMessage(mHandler.obtainMessage(MSG_LOAD_USER_LIST_DONE));
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Message msg = mHandler.obtainMessage(MSG_LOAD_DATA_ERROR, e.getMessage());
                                mHandler.sendMessage(msg);
                            }
                        }
                        if (jsonObject.has("mediaList")) {
                            try {
                                JSONArray mediaList = jsonObject.getJSONArray("mediaList");
                                final int count = mediaList.length();
                                mRawMediaList = new RawMediaItem[count];
                                for (int i = 0; i < count; i++) {
                                    RawMediaItem dataItem = new RawMediaItem();
                                    dataItem.decode(mediaList.getJSONObject(i));
                                    mRawMediaList[i] = dataItem;
                                }
                                mHandler.sendMessage(mHandler.obtainMessage(MSG_LOAD_MEDIA_LIST_DONE));
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Message msg = mHandler.obtainMessage(MSG_LOAD_DATA_ERROR, e.getMessage());
                                mHandler.sendMessage(msg);
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
            }
        });
        request.setTag("wx");
        mQueue.add(request);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.cancelAll("wx");
    }

    private void loadUserListDone() {
        mLlyUserList.removeAllViews();
        if (mUserList == null || mUserList.length == 0) {
            // 如果用户列表为空，不做任何处理
            return;
        }
        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        final int count = mUserList.length;
        for (int i = 0; i < count; i++) {
            UserItem item = mUserList[i];
            View itemView = inflater.inflate(R.layout.journal_avatar_item, null);
            TextView txvNickname = (TextView) itemView.findViewById(R.id.user_nickname);
            txvNickname.setText(item.nickName);
            ImageView imgAvatar = (ImageView) itemView.findViewById(R.id.user_avatar);
            mImageLoader.get(item.avatarSrc, ImageLoader.getImageListener(
                    imgAvatar, R.drawable.def_avatar, R.drawable.def_avatar));
            mLlyUserList.addView(itemView);
        }
    }

    private void loadDataError(String message) {
        //TODO 处理加载数据发生异常的情况
    }

    private void loadMediaListDone() {
        if (mRawMediaList == null || mRawMediaList.length == 0) {
            // 如果数据为空，不做任何处理
            return;
        }
        // 分组
        groupRawDataWithDate(0, mRawMediaList.length);
        mLookup.setItemList(mItems);
        mAdapter.appendList(mItems);
    }

    // 按日期分组
    private void groupRawDataWithDate(int start, int end) {
        mItems = new ArrayList<>(end - start);
        // 记录遍历的日期
        String currentDate = null;
        // 记录一天分组的配置
        int groupPosition = 0;
        for (int i = start; i < end; i++) {
            RawMediaItem curr = mRawMediaList[i];
            String date = curr.date;
            if (currentDate == null || !currentDate.equals(date)) {
                currentDate = date;

                DateItem item = new DateItem();
                item.dateText = currentDate;
                mItems.add(item);

                groupPosition = 0;
            }

            CoverItem item = new CoverItem();
            item.id = curr.id;
            item.positonAtList = i;
            item.positionOnRow = groupPosition % DEFAULT_SPAN_COUNT;
            item.avatarSrc = curr.avatarSrc;
            item.iconSrc = curr.iconSrc;
            item.mediaSrc = curr.mediaSrc;
            item.dateText = curr.date;
            item.mediaType = curr.mediaType;
            item.isEditMode = isbianji;
            mItems.add(item);

            groupPosition++;
        }
    }

    private static class UserItem {
        String nickName;
        String avatarSrc;

        void decode(JSONObject json) {
            try {
                nickName = json.getString("nickName");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                avatarSrc = json.getString("avatar");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private static class RawMediaItem {
        long id;
        int mediaType;
        String mediaSrc;
        String avatarSrc;
        String iconSrc;
        String date;

        void decode(JSONObject json) {
            try {
                id = json.getInt("mediaId");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                mediaType = "img".equals(json.getString("mediaType")) ?
                        COVER_TYPE_IMAGE : COVER_TYPE_VIDEO;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                mediaSrc = json.getString("src");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                avatarSrc = json.getString("avatar");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                iconSrc = json.getString("iconSrc");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                date = json.getString("uploadDate");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private static abstract class BaseItem {
        int type;           // 元素类型
        int positionOnRow = 0;  // 在一行中的位置
        long id = -1;

        void bindViewHolder(BaseViewHolder vh) {
            onBindViewHolder(vh);
        }

        abstract void onBindViewHolder(BaseViewHolder vh);
    }

    private static class DateItem extends BaseItem {
        String dateText;    // 日期

        DateItem() {
            this.type = ITEM_TYPE_DATE;
        }

        @Override
        void onBindViewHolder(BaseViewHolder vh) {
            vh.txvDate.setText(dateText);
        }
    }

    private static class CoverItem extends BaseItem {

        String iconSrc;     // 封面图片地址
        String avatarSrc;   // 头像图片地址
        String dateText;    // 日期
        String mediaSrc;    // 大图或者视频源地址
        int positonAtList;  // 在大列表中位置
        int mediaType;      // 图片 or 视频
        boolean isEditMode; // true 表示编辑状态，显示垃圾筐按钮，false 表示不显示

        CoverItem() {
            this.type = ITEM_TYPE_COVER;
            this.isEditMode = false;
        }

        @Override
        void onBindViewHolder(BaseViewHolder vh) {
            CoverViewHolder holder = (CoverViewHolder) vh;
            holder.txvDate.setText(dateText);
            // 视频显示播放标记，照片不需要显示
            holder.imgVideoFlag.setVisibility(
                    this.mediaType == COVER_TYPE_VIDEO ? View.VISIBLE : View.GONE);
            // 如果是编辑状态，显示垃圾筐按钮，否则不显示
            holder.item_relayout.setVisibility(
                    this.isEditMode ? View.VISIBLE : View.GONE);
            holder.imgVideoFlag.setImageResource(
                    this.isEditMode ? R.drawable.video_tubiao2 : R.drawable.video_tubiao
            );
        }
    }

    private interface CoverListAdapterDelegate {

        void onScorllToListItem(long id);

        void onScorllToFirstRow();
    }

    private class CoverListAdapter extends RecyclerView.Adapter<BaseViewHolder> {

        private Context mContext = null;
        private List<BaseItem> mItemList = new ArrayList<>();
        private final Resources mRes;
        private CoverListAdapterDelegate mDelegate = null;
        private boolean mIsFirst = true;

        public CoverListAdapter(Context context, CoverListAdapterDelegate delegate) {
            mContext = context;
            mRes = mContext.getResources();
            mDelegate = delegate;
        }

        void appendList(List<BaseItem> list) {
            mItemList = list;
            notifyDataSetChanged();
        }

        @Override
        public long getItemId(int position) {
            return super.getItemId(position);
        }

        @Override
        public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            BaseViewHolder viewHolder = null;
            switch (viewType) {
                case ITEM_TYPE_DATE: {
                    TextView tv = new TextView(mContext);
                    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,mRes.getDimensionPixelSize(R.dimen.chengzhang_ziti));
                    tv.setTextColor(Color.WHITE);
                    RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
                            MATCH_PARENT, WRAP_CONTENT);
                    tv.setLayoutParams(lp);
                    viewHolder = new DateViewHolder(tv);
                }
                    break;
                case ITEM_TYPE_COVER: {
                    View itemView = LayoutInflater.from(mContext).inflate(
                            R.layout.journal_cover_item, null);
                    final int itemWidth = mRes.getDimensionPixelSize(R.dimen.journal_cover_item_width);
                    final int itemHeight = mRes.getDimensionPixelSize(R.dimen.journal_cover_item_height);
                    RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(itemWidth, itemHeight);
                    itemView.setLayoutParams(lp);
                    viewHolder = new CoverViewHolder(itemView);
                }
                    break;
                default:
                    throw new IllegalArgumentException(
                            "ViewType 必须是 ITEM_TYPE_DATE 或者 ITEM_TYPE_COVER");
            }
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(BaseViewHolder holder, int position) {
            final BaseItem item = getItem(position);
            item.bindViewHolder(holder);

            if (item instanceof CoverItem) {
                // 加载封面图片以及微信头像图片
                CoverItem ci = (CoverItem) item;
                CoverViewHolder vh = (CoverViewHolder) holder;
                vh.onBind(ci);
                final int avatarMaxSize = mRes.getDimensionPixelSize(R.dimen.journal_cover_avatar_size);
                mImageLoader.get(ci.avatarSrc, ImageLoader.getImageListener(
                                vh.imgAvatar, R.drawable.def_avatar, R.drawable.def_avatar),
                        avatarMaxSize, avatarMaxSize);

                final int coverMaxWidth = mRes.getDimensionPixelSize(R.dimen.journal_cover_item_width);
                final int coverMaxHeight = mRes.getDimensionPixelSize(R.dimen.journal_cover_item_height);
                mImageLoader.get(ci.iconSrc, ImageLoader.getImageListener(
                                vh.imgCover, R.drawable.def_cover_bg, R.drawable.def_cover_bg),
                        coverMaxWidth, coverMaxHeight, ImageView.ScaleType.CENTER_CROP);
                vh.imgFocusMask.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus && ((CoverItem) item).positonAtList < DEFAULT_SPAN_COUNT) {
                            if (mDelegate != null) {
                                mDelegate.onScorllToFirstRow();
                            }
                        }
                    }
                });
                vh.setOnCoverItemClickListener(new OnCoverItemClickListener() {

                    @Override
                    public void onItemClick(View view, int position) {

                        final int count = getItemCount();
                        ArrayList<String> mediaSrcList = new ArrayList<>();
                        ArrayList<String> mediaTypeList = new ArrayList<>();
                        ArrayList<String> iconSrcList = new ArrayList<>();
                        for (int i = 0; i < count; i++) {
                            final BaseItem item = getItem(i);
                            if (item.type == ITEM_TYPE_DATE) {
                                continue;
                            }

                            CoverItem ci = (CoverItem) item;
                            mediaSrcList.add(ci.mediaSrc);
                            iconSrcList.add(ci.iconSrc);
                            mediaTypeList.add(ci.mediaType == COVER_TYPE_VIDEO ? "video" : "img");
                        }

                        Intent intent = new Intent();
                        intent.setClass(mContext, ChengzhangrijiNeirongActivity.class);
                        intent.putExtra("position", position);
                        intent.putExtra("urls", mediaSrcList);
                        intent.putExtra("urls2", mediaTypeList);
                        intent.putExtra("urls3", iconSrcList);
                        startActivity(intent);
                    }

                    @Override
                    public void onItemDelete(View view, int position, CoverItem item) {
                        // TODO
                        String mediatype=null;
                        int type=item.mediaType;
                        if(type==COVER_TYPE_IMAGE){
                            mediatype="img";
                        }else{
                            mediatype="video";
                        }
                        long id=item.id;
                        RequestQueue rq = Volley.newRequestQueue(JournalActivity.this.getApplicationContext());
                        StringRequest request = new StringRequest("http://121.201.14.248/wangwangba/updateData.jsp?mediaType="+mediatype+"&mediaId="+id,
                                new Response.Listener<String>() {

                                    @Override
                                    public void onResponse(String jsonObject) {
                                        jsonObject=jsonObject.replaceAll("\n", "");
                                        jsonObject=jsonObject.replaceAll("\r", "");
                                        if(jsonObject.equals("true")) {
                                            loadData();
                                            chengzhangriji_wancheng_iv.requestFocus();
                                        }else{
                                            Toast.makeText(JournalActivity.this,"删除失败",Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                            }
                        }

                        );
                        rq.add(request);

                    }
                });
                if (ci.positonAtList == 0 && mIsFirst) {
                    mIsFirst = false;
                    vh.imgFocusMask.requestFocus();
                }
                if(ci.positonAtList==0){
                    CoverViewHolder holder1= (CoverViewHolder) holder;
                    holder1.imgFocusMask.setTag("firstitem");
                }else{
                    CoverViewHolder holder1= (CoverViewHolder) holder;
                    holder1.imgFocusMask.setTag(null);
                }
            }
        }

        @Override
        public int getItemCount() {
            return mItemList != null ? mItemList.size() : 0;
        }

        BaseItem getItem(int position) {
            return mItemList.get(position);
        }

        @Override
        public int getItemViewType(int position) {
            return mItemList != null ? mItemList.get(position).type : 0;
        }

        /** 打开编辑模式 */
        void onEditMode() {
            setEditable(true);
        }

        /** 关闭编辑模式 */
        void offEditMode() {
            setEditable(false);
        }

        /**
         * 设置编辑模式
         * @param editable true 表示进入编辑模式界面，否则为正常界面
         */
        private void setEditable(boolean editable) {
            if (mItemList != null && mItemList.size() > 0) {
                for (BaseItem item : mItemList) {
                    if (item instanceof CoverItem) {
                        ((CoverItem) item).isEditMode = editable;
                    }
                }
            }
            this.notifyDataSetChanged();
        }
    }

    private abstract class BaseViewHolder extends RecyclerView.ViewHolder {

        protected TextView txvDate;

        public BaseViewHolder(View itemView) {
            super(itemView);
            txvDate = getDateTextView(itemView);
        }

        abstract TextView getDateTextView(View itemView);
    }

    private class DateViewHolder extends BaseViewHolder {

        public DateViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        TextView getDateTextView(View itemView) {
            return (TextView) itemView;
        }
    }

    private interface OnCoverItemClickListener {

        void onItemClick(View view, int position);

        void onItemDelete(View view, int position, CoverItem item);
    }

    private class CoverViewHolder extends BaseViewHolder implements View.OnClickListener {

        ImageView imgCover;
        ImageView imgAvatar;
        ImageView imgVideoFlag;
        FocusImageView imgFocusMask;
        RelativeLayout item_relayout;
        private OnCoverItemClickListener mListener;
        private CoverItem mDataItem = null;

        public CoverViewHolder(View itemView) {
            super(itemView);
            imgCover = (ImageView) itemView.findViewById(R.id.journal_cover);
            imgAvatar = (ImageView) itemView.findViewById(R.id.journal_avatar);
            imgVideoFlag = (ImageView)itemView.findViewById(R.id.journal_video_flag);
            imgFocusMask = (FocusImageView) itemView.findViewById(R.id.focus_mask);
            item_relayout = (RelativeLayout)itemView.findViewById(R.id.item_relayout);
            imgFocusMask.clearBackgroundShadow();
            imgFocusMask.setOnClickListener(this);
        }

        @Override
        TextView getDateTextView(View itemView) {
            return (TextView) itemView.findViewById(R.id.journal_date);
        }

        void onBind(CoverItem dataItem) {
            mDataItem = dataItem;
        }

        void setOnCoverItemClickListener(OnCoverItemClickListener l) {
            mListener = l;
        }

        @Override
        public void onClick(View v) {
            if (!mDataItem.isEditMode) {
                if (mListener != null) {
                    mListener.onItemClick(this.itemView, mDataItem.positonAtList);
                }
            } else {
                if (mListener != null) {
                    mListener.onItemDelete(this.itemView, mDataItem.positonAtList, mDataItem);
                }
            }
        }
    }

    private class CoverListSpanSizeLookup extends GridLayoutManager.SpanSizeLookup {

        private List<BaseItem> mItemList = null;

        CoverListSpanSizeLookup() {
        }

        void setItemList(List<BaseItem> list) {
            mItemList = list;
        }

        @Override
        public int getSpanSize(int position) {
            if (mItemList == null || mItemList.isEmpty()) {
                return 0;
            }
            return mItemList.get(position).type == ITEM_TYPE_DATE ? DEFAULT_SPAN_COUNT : 1;
        }

        @Override
        public int getSpanIndex(int position, int spanCount) {
            return mItemList.get(position).positionOnRow;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(chengzhangriji_bianji_iv.isFocused() || chengzhangriji_wancheng_iv.isFocused()){
            final int N = mRycMediaList.getChildCount();
            CoverViewHolder viewHolder = null;
            for (int i = 0; i < N; i++) {
                final View child = mRycMediaList.getChildAt(i);
                RecyclerView.ViewHolder vh = mRycMediaList.getChildViewHolder(child);
                if (vh instanceof CoverViewHolder) {
                    viewHolder = (CoverViewHolder) vh;
                    break;
                }
            }
            if (viewHolder != null) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    FocusImageView v = viewHolder.imgFocusMask;
                    if (v != null) {
                        v.requestFocus();
                    }
                }
                if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                    FocusImageView v = viewHolder.imgFocusMask;
                    if (v != null) {
                        v.requestFocus();
                    }
                }
            }
            return  true;
        }else{
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        mMessengerClient.subscribeMessage(this, mMessageSubscriber);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mMessengerClient.unsubscribeMessage(mMessageSubscriber);
    }

    private class MessageSubscriberImpl extends MessageSubscriber {

        @Override
        public void onReceiveMessage(Context context, String tag, Letter message) {
            if (tag.equals("wangwangba.journal.add")) {
                //TODO 用户在微信客户端发照片或视频后会收到通知
                RawMediaItem dataItem = new RawMediaItem();
                dataItem.decode(message.getData());
                final int length = mRawMediaList != null ? mRawMediaList.length : 0;
                final RawMediaItem[] old = mRawMediaList;
                mRawMediaList = new RawMediaItem[length + 1];
                mRawMediaList[0] = dataItem;
                if (length > 0) {
                    System.arraycopy(old, 0, mRawMediaList, 1, length);
                }
                mHandler.sendMessage(mHandler.obtainMessage(MSG_LOAD_MEDIA_LIST_DONE));
            }
        }
    }
}
